package com.llkj.qingnianguoxue.course;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jm.call.CallActivity;
import com.jm.chat.application.JGApplication;
import com.jm.chat.pickerimage.utils.StringUtil;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.CourseEvaluateAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CourseEvaluateBean;
import com.llkj.qingnianguoxue.bean.CurriculumDetailsBean;
import com.llkj.qingnianguoxue.bean.RxCoursePayBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.mine.mycourse.VideoCallCourseActivity;
import com.llkj.qingnianguoxue.music.PublicCommentActivity;
import com.llkj.qingnianguoxue.util.DateUtils;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jiguang.jmrtc.api.JMSignalingMessage;
import rx.functions.Action1;

import static com.jm.call.JMRtcClientManager.CALL_VIDEO;
import static com.llkj.qingnianguoxue.base.ConstantUserInfo.USER_IDENTITY_TYPE;

public class CourseDetailActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener,View.OnClickListener {
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView lvEvaluateView;//评价
    @BindView(R.id.btnBookingCourse)
    TextView btnBookingCourse;//立即预约

    private ImageView ivCover;
    private TextView tvDetail,tvSpeaker,tvCourseTime,tvCoursePrice;

    private CourseEvaluateAdapter mEvaluateAdapter;
    private List<CourseEvaluateBean> mEvaluateData;
    private String mTitle;
    private int totalSize,mPage;
    private String mCourseId;//课程id
    private String mIdentityType,mIsReverse;//mIdentityType身份1普通，2老师，// mIsReverse预约状态 1 本人已预约    2 其他用户已预约 3 没有人预约
    private String mCoursePicUrl,mCourseTime,mCourseMoney;//封面图，课程名，课程时间安排，课程金额
    private String mFriendChatId,mMasterId;//视频聊天id,开课老师id
    private int mFromView;//来自哪个界面1我的课程
    private long mCourseEndTime;//课程结束时间

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_detail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        Intent intent = getIntent();
        mTitle = intent.getStringExtra("title");
        mCourseId = intent.getStringExtra("id");
        mFromView = intent.getIntExtra("type",0);
        if(StringUtil.isEmpty(mTitle)){
            mTitle = "课程详情";
        }
        setTitle(mTitle, true, TITLE_TYPE_IMG, R.drawable.icon_back, false, -1, -1);

        initView();
        initListener();

        onRefresh();
    }

    private void initView(){
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvEvaluateView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mEvaluateData = new ArrayList<>();
        mEvaluateAdapter = new CourseEvaluateAdapter(R.layout.item_course_evaluate,mEvaluateData);
        lvEvaluateView.setAdapter(mEvaluateAdapter);

        View viewHeader = LayoutInflater.from(this).inflate(R.layout.header_course_detail,null);
        ivCover = (ImageView) viewHeader.findViewById(R.id.ivCover);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) ivCover.getLayoutParams();
        params.height = DisplayUtil.getDensityWdith(this)*320/640;

        tvDetail = (TextView) viewHeader.findViewById(R.id.tvCourseDetial);
        tvSpeaker = (TextView) viewHeader.findViewById(R.id.tvSpeaker);
        tvCourseTime = (TextView) viewHeader.findViewById(R.id.tvCourseTime);
        tvCoursePrice = (TextView) viewHeader.findViewById(R.id.tvCoursePrice);
        mEvaluateAdapter.addHeaderView(viewHeader);

        refreshLayout.setOnRefreshListener(this);
        mEvaluateAdapter.setOnLoadMoreListener(this);
        btnBookingCourse.setOnClickListener(this);
    }

    private void initListener(){
//        RxBus.getInstance().toObservable(RxCoursePayBean.class).subscribe(new Action1<RxCoursePayBean>() {
//            @Override
//            public void call(RxCoursePayBean bean) {
//                if (bean.isPaySuccess){
////                    mIsReverse = "1";
////                    setStateBtn();
//                    loadWaitDialog();
//                    onRefresh();
//                }
//            }
//        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void bookCourseResult(RxCoursePayBean rxCoursePayBean){
        loadWaitDialog();
        onRefresh();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getCurriculumDetails();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, mEvaluateAdapter, null, lvEvaluateView, totalSize);
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getCurriculumDetails();
    }

    @Override
    public void onClick(View view) {
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            dialogConfirm(null, null, null, null).show();
            return;
        }
        switch (view.getId()){
            case R.id.btnBookingCourse:
                if("1".equals(mIdentityType)){//普通身份
                    if("1".equals(mIsReverse)){//去听课
//                    mFriendChatId = "qcgx_8";
//                        Intent intent = new Intent(this,CallActivity.class);
//                        intent.putExtra(CALL_VIDEO,"video");
//                        intent.putExtra("ChatId",mFriendChatId);
//                        startActivity(intent);
                    }else if("3".equals(mIsReverse)){//立即预约
                        CoursePayActivity.startActivity(this,0,mCourseId,mCoursePicUrl,mTitle,mCourseTime,mCourseMoney);
                    }else if("4".equals(mIsReverse)){//去评价
                        PublicCommentActivity.startActivity(this,mMasterId,1);
                    }
                }else if("2".equals(mIdentityType)){//老师
                    String masterId = MyApplication.getInstance().sputil.getString(ConstantUserInfo.MASTER_ID);
                    if(masterId.equals(mMasterId) && "2".equals(mIsReverse)){
                        Intent intent = new Intent(this,CallActivity.class);
                        intent.putExtra(CALL_VIDEO,"video");
                        intent.putExtra("ChatId",mFriendChatId);
                        intent.putExtra("endTime",mCourseEndTime);
                        startActivity(intent);
                    }
                }
                break;
        }
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivity(LoginActivity.class);
    }

    private void getCurriculumDetails(){
        HttpMethod.curriculumDetails(this,this, String.valueOf(mPage),mCourseId);
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            return;
        }
        setStateBtn();
    }

    private void setStateBtn(){
        mIdentityType = MyApplication.getInstance().sputil.getString(USER_IDENTITY_TYPE);
        btnBookingCourse.setSelected(false);
        if("1".equals(mIdentityType)){
            if("2".equals(mIsReverse)){
                btnBookingCourse.setSelected(true);
//                btnBookingCourse.setClickable(false);
                btnBookingCourse.setText("已被预约");
            }else if("1".equals(mIsReverse)){
                if(mFromView==1){
                    btnBookingCourse.setSelected(true);
                    btnBookingCourse.setText("课程未开始");
                }else{
                    btnBookingCourse.setSelected(true);
                    btnBookingCourse.setText("已预约");
                }
            }else if("3".equals(mIsReverse)){
                btnBookingCourse.setText("立即预约");
            }else if("4".equals(mIsReverse)){
                btnBookingCourse.setText("去评价");
            }else if("5".equals(mIsReverse)){
                btnBookingCourse.setSelected(true);
                btnBookingCourse.setText("已完结");
            }else{
                btnBookingCourse.setSelected(true);
                btnBookingCourse.setText("立即预约");
            }

        }else if("2".equals(mIdentityType)){
            String masterId = MyApplication.getInstance().sputil.getString(ConstantUserInfo.MASTER_ID);
            if(masterId.equals(mMasterId)){
                if("1".equals(mIsReverse) || "2".equals(mIsReverse)){
                    btnBookingCourse.setText("去开课");
                    btnBookingCourse.setSelected(false);
                }else if("3".equals(mIsReverse)){
                    btnBookingCourse.setSelected(true);
                    btnBookingCourse.setText("未预约");
                }else if("4".equals(mIsReverse)){
                    btnBookingCourse.setSelected(true);
                    btnBookingCourse.setText("已完结");
                }else if("5".equals(mIsReverse)){
                    btnBookingCourse.setSelected(true);
                    btnBookingCourse.setText("已完结");
                }else{
                    btnBookingCourse.setSelected(true);
                    btnBookingCourse.setText("未预约");
                }
            }else{
                btnBookingCourse.setSelected(true);
                btnBookingCourse.setText("立即预约");
            }
        }
        btnBookingCourse.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_CURRICULUM_DETAILS) {
            CurriculumDetailsBean detailBean = GsonUtil.GsonToBean(data, CurriculumDetailsBean.class);
            if (detailBean != null) {
                if(detailBean.getCurriculum()!=null){
                    if(StringUtils.isEmpty(detailBean.getCurriculum().getName())){
                        mTitle = detailBean.getCurriculum().getName();
                        tvTitle.setText(mTitle);
                    }
                    mCoursePicUrl = detailBean.getCurriculum().getImg();
                    mCourseTime = detailBean.getCurriculum().getStart_time()+"-"+detailBean.getCurriculum().getEnd_time();
                    mCourseMoney = detailBean.getCurriculum().getPrice();
                    ImageLoadingUtil.loadingUrl(ivCover,mCoursePicUrl);
                    tvDetail.setText("课程简介："+detailBean.getCurriculum().getAbstractX());
                    tvSpeaker.setText("主讲人："+detailBean.getCurriculum().getMaster_name());
                    tvCourseTime.setText("课程安排："+mCourseTime);
                    tvCoursePrice.setText(String.format(getString(R.string.book_course_price),mCourseMoney));

//                    if("1".equals(mIdentityType)){//普通用户
//                    mFriendChatId = detailBean.getCurriculum().getMaster_jgid();
                    mMasterId = detailBean.getCurriculum().getMaster_id();
//                    }else if("2".equals(mIdentityType)){//老师身份
                        mFriendChatId = detailBean.getCurriculum().getUser_jgid();
//                    }

                    mIsReverse = detailBean.getCurriculum().getIs_reserve();
//                    //判断处理已过期的课程
                    Date date = DateUtils.dateFormat(detailBean.getCurriculum().getEnd_time());
                    mCourseEndTime = date.getTime();
                    String bookUserID = detailBean.getCurriculum().getUser_jgid();
                    String myUserID = MyApplication.getInstance().sputil.getString(ConstantUserInfo.CHAT_LOGIN_ID);
                    if(date!=null && System.currentTimeMillis()>date.getTime() && myUserID.equals(bookUserID)){
                        mIsReverse = "4";
                    }else if(System.currentTimeMillis()>date.getTime()){
                        mIsReverse = "5";
                    }
                    setStateBtn();
                }

                totalSize = Integer.parseInt(detailBean.getNum());
                if (mPage == 1) {
                    mEvaluateData.clear();
                    LoadDataHelper.refreshComplete(mEvaluateAdapter, mEvaluateData, refreshLayout, lvEvaluateView);
                } else {
                    mEvaluateAdapter.setEnableLoadMore(true);
                    mEvaluateAdapter.loadMoreComplete();
                }
                mEvaluateData.addAll(detailBean.getComment());
                mEvaluateAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
